package lk.icta.core.dao.impl;

import lk.icta.common.dao.impl.BaseDAO;
import lk.icta.core.dao.ScheduleDAO;
import lk.icta.core.entity.Schedule;
import lk.icta.user.entity.User;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.Date;
import java.util.List;

/**
 * @author Duminda Dharmakeerthi
 */
public class ScheduleDAOImpl extends BaseDAO implements ScheduleDAO {

    @Transactional(propagation = Propagation.MANDATORY)
    public void addSchedule(Schedule schedule, User user) {
        logger.debug("Adding a Schedule {}", schedule.getId());
        schedule.getLifeCycleInfo().setCreatedTimeStamp(new Date());
        schedule.getLifeCycleInfo().setCreatedUser(user);
        schedule.getLifeCycleInfo().setLastUpdatedTimeStamp(new Date());
        schedule.getLifeCycleInfo().setLastUpdatedUser(user);
        em.persist(schedule);
    }

    @Transactional(propagation = Propagation.MANDATORY)
    public void updateSchedule(Schedule schedule, User user) {
        logger.debug("Updating a Schedule {}", schedule.getId());
        schedule.getLifeCycleInfo().setLastUpdatedTimeStamp(new Date());
        schedule.getLifeCycleInfo().setLastUpdatedUser(user);
        em.merge(schedule);
    }

    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public List<Schedule> getAllActiveSchedule(Schedule.Status status) {
        Query q = em.createNamedQuery("getAllActiveSchedule");
        q.setParameter("status", status);
        return q.getResultList();
    }

    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public List<Schedule> getAllActiveSchedulesByDSDivision(Schedule.Status status, int dsDivisionId) {
        Query q = em.createNamedQuery("getAllActiveSchedulesByDSDivision");
        q.setParameter("status", status);
        q.setParameter("dsDivisionId", dsDivisionId);
        return q.getResultList();
    }

    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public Schedule getScheduleById(int id) {
        Query q = em.createNamedQuery("getScheduleById");
        q.setParameter("id", id);
        return (Schedule) q.getSingleResult();
    }

    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public List<Schedule> getScheduleByDate(Date startDate) {
        Query q = em.createNamedQuery("getScheduleByDate");
        q.setParameter("startDate", startDate);
        return q.getResultList();
    }

    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public List<Schedule> getScheduleByLandId(long landId) {
        Query q = em.createNamedQuery("getScheduleByLandId");
        q.setParameter("landId", landId);
        return q.getResultList();
    }
}
